﻿using System;
using System.IO;

namespace Medora.Core
{

    public static class Logger
    {
        /// <summary>
        /// The locker
        /// </summary>
        private static readonly object locker = new object();

        /// <summary>
        /// The filename
        /// </summary>
        private static string filename = @"/logfile_" + DateTime.Today.Year + @"_" + DateTime.Today.Month + @"_" + DateTime.Today.Day + @".log";
        /// <summary>
        /// The directory
        /// </summary>
        private static string directory = Settings.LogDirectory;

        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <exception cref="System.Exception"></exception>
        public static void WriteLog(string message)
        {
#if (DEBUG)
            lock (locker)
            {

                if (Directory.Exists(directory))
                {
                    try
                    {
                        using (var writer = new StreamWriter(directory + filename, true))
                        {
                            writer.WriteLine(string.Format("{0} {1}: {2}", DateTime.Now.ToShortDateString(),
                                                           DateTime.Now.ToShortTimeString(), message));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

                }
            }
#endif
        }

        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="e">The e.</param>
        /// <exception cref="System.Exception"></exception>
        public static void WriteLog(Exception e)
        {
            lock (locker)
            {

                if (Directory.Exists(directory))
                {
                    try
                    {
                        using (var writer = new StreamWriter(directory + filename, true))
                        {
                            string message = string.Format("Message: {0}, InnerMessage: {1}", "" + e,
                                                           e.InnerException != null
                                                               ? e.InnerException.Message
                                                               : string.Empty);
                            writer.WriteLine(string.Format("{0} {1}: Exception: {2}", DateTime.Now.ToShortDateString(),
                                                           DateTime.Now.ToShortTimeString(), message));
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }


        }
    }

}